package admin.core.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {

    private static final String PROPERTIES = "jdbc.properties";

    private static String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static String URL = "jdbc:mysql://localhost:3306/public";
    private static String USERNAME = "root";
    private static String PASSWORD = "root";


    static {
        try (InputStream inStream = ClassLoader.getSystemClassLoader().getResourceAsStream(PROPERTIES);) {
            Properties properties = new Properties();
            properties.load(inStream);
            DRIVER = properties.getProperty("jdbc.driver");
            URL = properties.getProperty("jdbc.url");
            USERNAME = properties.getProperty("jdbc.username");
            PASSWORD = properties.getProperty("jdbc.password");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    public static Connection getConnection() throws Exception {
        Class.forName(DRIVER);
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);

    }


    public static void close(ResultSet rs, Statement state, Connection con) {

        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (state != null) {
                state.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
